<template>
  <div class="app-container">
    <h3 class="title">溯源商品管理</h3>
    <div v-if="setPermissionBtn('/traceabilityGoods/findList', searchBtn)" class="inputBox">
      <el-select v-model="search.categoryId" class="type" placeholder="请选择商品类型">
        <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-input v-model="search.goodName" class="input" placeholder="商品名称" />
      <el-date-picker
        v-model="search.startTime"
        class="startDate"
        type="date"
        value-format="yyyy-MM-dd"
        placeholder="选择开始日期"/>
      <el-date-picker
        v-model="search.endTime"
        class="endDate"
        type="date"
        value-format="yyyy-MM-dd"
        placeholder="选择结束日期"/>
      <el-select v-model="search.status" class="teacherStatus" placeholder="请选择商品状态">
        <el-option label="停用" value="0" />
        <el-option label="启用" value="1" />
      </el-select>
      <el-button type="primary" class="ml10" @click="toSearch">{{ searchBtn.btnName }}</el-button>
      <el-button type="primary" @click="toReset">重置</el-button>
    </div>
    <el-button v-if="setPermissionBtn('/traceabilityGoods/add', addBtn)" type="primary" class="addBtn" @click="add()">{{ addBtn.btnName }}</el-button>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="加载中请稍后"
      border
      fit
      highlight-current-row>
      <el-table-column label="商品编号">
        <template slot-scope="scope">
          {{ scope.row.number }}
        </template>
      </el-table-column>
      <el-table-column label="商品类型">
        <template slot-scope="scope">
          {{ scope.row.categoryName }}
        </template>
      </el-table-column>
      <el-table-column label="溯源商品">
        <template slot-scope="scope">
          {{ scope.row.goodName }}
        </template>
      </el-table-column>
      <el-table-column label="溯源环节" width="246px">
        <template slot-scope="scope">
          <el-button
            v-if="setPermissionBtn('/traceabilityGoods/selectOne', scope.row)"
            size="mini"
            type="warning"
            value="查看溯源环节"
            plain
            @click="see(scope.row.id, scope.$index)">{{ scope.row.btnName }}</el-button>
          <el-button
            v-if="setPermissionBtn('/traceabilityGoods/deploy', scope.row)"
            :disabled="scope.row.status === 1"
            size="mini"
            value="配置溯源环节"
            type="primary"
            plain
            @click="config(scope.row.id, scope.$index)">{{ scope.row.btnName }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="创建时间">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          {{ scope.row.status | formatStatus }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="操作" width="150">
        <template slot-scope="scope">
          <!-- <el-button
            v-if="setPermissionBtn('edit', scope.row)"
            :disabled="scope.row.status === 1"
            size="mini"
            value="编辑"
            type="primary"
            @click="edit(scope.row)">{{ scope.row.btnName }}</el-button> -->
          <el-button
            v-if="setPermissionBtn('enable/disable', scope.row)"
            :type="scope.row.status == 0?'success':'danger'"
            size="mini"
            value="启用/停用"
            @click="update(scope.row.id, scope.row.status)"
            v-html="splitName(scope.row.btnName, scope.row.status)"/>
          <!-- <el-button
            v-if="scope.row.status === 0"
            size="mini"
            type="success"
            @click="update(scope.row.id, '1')">启用</el-button>
          <el-button
            v-if="scope.row.status === 1"
            size="mini"
            type="danger"
            @click="update(scope.row.id, '0')">停用</el-button> -->
          <el-button
            v-if="setPermissionBtn('del', scope.row)"
            :disabled="scope.row.status === 1"
            size="mini"
            value="删除"
            type="danger"
            @click="del(scope.row.id)">{{ scope.row.btnName }}</el-button>
            <!-- <el-button
            size="mini"
            type="success"
          @click="refund(scope.row.oid, scope.row.tid, scope.row.orderCommission)">查看详情</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <!-- <remark :remark-list="remarkList" :remark-visible.sync="remarkVisible" :remark-index="remarkIndex" /> -->
    <!-- <remarkPropt
      ref="remarke"
      :remark-propt-list="remarkProptList"
      :remark-propt-visible.sync="remarkProptVisible"
      :remark-propt-index="remarkProptIndex"
      :remark-type="-1"
      @remarkText="remarkText" /> -->
    <detail :detialvisible.sync="dialogTableVisible" :dialogdata.sync="list" :myindex.sync="detailIndex" :detail-mode="'address'" />
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="fetchData" />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
// import BankView from '@/components/Dialog/BankView'
import detail from '@/components/detail'
import Dialog from '@/components/Dialog'
import { Message } from 'element-ui'
import { getOrderList, selectCard, addRemark, getRemarkPage } from '@/api/order'
import { getLocalUid, setLocalUid, getLocalId, setLocalId } from '@/utils/uid'
import { getPermission } from '@/api/permission'
import { getLocalUserName, setLocalUserName } from '@/utils/uid'
import remark from '@/components/remark'
import remarkPropt from '@/components/remark/remarkPrompt'
import { getAddressList, addressUpdate } from '@/api/address'
import { categoryQuery } from '@/api/product'
import { getSuYuanGoodsList, updateYuanGoods, delSuYuanGood } from '@/api/source'

export default {
  components: { Pagination, Dialog, detail, remarkPropt },
  filters: {
    // statusFilter(status) {
    //   const statusMap = {
    //     published: 'success',
    //     draft: 'gray',
    //     deleted: 'danger'
    //   }
    //   return statusMap[status]
    // },
    // 等于之前的level
    formatStatus(status) {
      const StatusMap = {
        0: '停用',
        1: '启用'
      }
      return StatusMap[status]
    },
    nullStr(str) {
      if (str === '' || str === null) {
        return '-'
      } else {
        return str
      }
    }
  },
  data() {
    return {
      searchBtn: {},
      // visible: false,
      remarkProptVisible: false,
      remarkProptList: [],
      remarkProptIndex: -1,
      userName: '',
      userType: -1,
      list: [
        // {
        //   categoryName: '商品类型1',
        //   goodName: '溯源商品1',
        //   createTime: '创建时间1',
        //   status: 1
        // }
      ],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 0,
        pageSize: 10
      },
      search: {
        categoryId: '',
        goodName: '',
        startTime: '',
        endTime: '',
        status: ''
      },
      dialogFormVisible: false,
      dialogTableVisible: false,
      detailIndex: -1,
      permissionShow: false, // 权限数据未到达之前按钮隐藏
      // permissionList: [] // 权限数据列表
      categoryList: [],
      addBtn: {}
    }
  },
  computed: {
    // 权限按钮 computed
    setPermissionBtn() {
      return function(str, row) {
        let index = -1
        const buttonList = this.$store.getters.button
        index = buttonList.findIndex(item => item.value === str)
        // console.log(index)
        if (index !== -1) {
          row.btnName = buttonList[index].name
          return true
        } else {
          return false
        }
      }
    },
    splitName() {
      return function(name, status) {
        console.log('name:', name)
        console.log('status:', status)
        const nameArr = name.split('/')
        if (status === 0) {
          return nameArr[0]
        } else {
          return nameArr[1]
        }
      }
    }
  },
  watch: {
    'permissionList'(newVal) {
      this.permissionList = newVal
      this.permissionShow = true
    }
  },
  created() {
    this.getCategory()
    this.getUserType()
    this.fetchData()
    // this.getPermissonFn()
  },
  mounted() {
    this.getPermissonFn() // 获取按钮权限 vuex的button
  },
  methods: {
    // 权限数据的获取
    // getPermissonFn() {
    //   const id = getLocalId()
    //   const uid = getLocalUid()
    //   const data = { uid }
    //   getPermission(id, data).then(res => {
    //     console.log('权限结果', res)
    //     if (res.code === '200') {
    //       this.permissionList = res.data
    //       // console.log('权限名称：', this.getPermissionName(this.permissionList))
    //     } else {
    //       Message.error(res.message + '-' + res.data)
    //     }
    //   })
    // },
    see(id, index) {
      const obj = Object.assign({ isLook: true }, this.list[index])
      this.$router.push({
        path: '/source/sourceGoodsConfig',
        query: obj
      })
    },
    config(id, index) {
      const obj = Object.assign({ isConfig: true }, this.list[index])
      this.$router.push({
        path: '/source/sourceGoodsConfig',
        query: obj
      })
    },
    // 备注a
    changeRemarks(uid, id, index) {
      this.remarkProptIndex = index
      console.log('--->', uid, id, index)
      const userData = ''
      this.remarkProptVisible = true
      this.$refs.remarke.request(uid, id)
    },
    remarkText() {
      this.fetchData()
    },
    getUserType() {
      switch (getLocalUserName()) {
        case 'admin':
          this.userType = 1
          break;
        case 'sale':
          this.userType = 2
          break;
        case 'casher':
          this.userType = 3
          break;
      }
    },
    // 查询
    toSearch() {
      if (this.search.startTime && this.search.endTime) {
        const start = new Date(this.search.startTime).getTime();
        const end = new Date(this.search.endTime).getTime();
        if (start > end) {
          Message.error('结束时间必须大于开始时间')
          return false
        }
      }
      if (this.search.startTime && this.search.startTime.indexOf(' 00:00:00') === -1) this.search.startTime += ' 00:00:00'
      if (this.search.endTime && this.search.endTime.indexOf(' 23:59:59') === -1) this.search.endTime += ' 23:59:59'
      this.listLoading = true
      console.log(this.search)
      const newData = this.objectCon(this.listQuery, this.search)
      // console.log(this.search.startTime)
      // console.log(this.search.endTime)
      getSuYuanGoodsList(newData).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    // 重置
    toReset() {
      this.search.categoryId = ''
      this.search.goodName = ''
      this.search.startTime = ''
      this.search.endTime = ''
      this.search.status = ''
    },
    // isDialog(a) {
    //   this.visible = false
    //   this.showDialog = false
    // },
    fetchData() {
      this.listLoading = true
      const newData = this.objectCon(this.listQuery)
      console.log('newData:=>', newData)
      getSuYuanGoodsList(newData).then(response => {
        if (response.code === '200') {
          this.list = response.data.list
          console.log('订单数据：', this.list)
          this.total = response.data.total
          setTimeout(() => {
            this.listLoading = false
          }, 0.5 * 1000)
        } else {
          Message.error(response.message + '-' + response.data)
          this.listLoading = false
        }
      })
    },
    add() {
      this.$router.push({
        path: '/source/sourceGoodsAdd',
        query: { isEdit: false }
      })
    },
    edit(row) {
      const query = { isEdit: true, data: row }
      this.$router.push({
        path: '/source/sourceGoodsAdd',
        query
      })
    },
    del(id) {
      this.$confirm('是否删除此溯源商品', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        const data = { status: 0, id }
        delSuYuanGood(data).then(res => {
          if (res.code === '200') {
            Message.success('删除成功')
            this.fetchData()
          } else {
            Message.error(res.message + res.data)
          }
        })
      })
    },
    update(id, type) {
      const strAsk = type === 0 ? '是否启用？' : '是否停用？'
      const str = type === 0 ? '已启用' : '已停用'
      this.$confirm(strAsk, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        type === 0 ? type = 1 : type = 0
        const data = { status: type, id }
        updateYuanGoods(data).then(res => {
          if (res.code === '200') {
            Message.success(str)
            this.fetchData()
          } else {
            Message.error(res.message + res.data)
          }
        })
      })
    },
    // 获取所有分类信息
    getCategory() {
      categoryQuery().then(res => {
        // console.log('获取所有分类信息:', res)
        if (res.code === '200') {
          this.categoryList = res.data
        }
      })
    }
  }
}
</script>
<style lang="scss">
  .inputBox{
    div{ margin-bottom: 10px;}
    .el-input, .el-select{
        width: 170px;
    }
  }
  .addBtn{
      margin-bottom: 20px;
  }
</style>
